package com.alibaba.nacos.config.server.jpa.service.impl;

import java.util.List;
import java.util.stream.Collectors;

import com.alibaba.nacos.config.server.auth.RoleInfo;
import com.alibaba.nacos.config.server.jpa.entity.RolesEntity;
import com.alibaba.nacos.config.server.jpa.repository.RolesRepository;
import com.alibaba.nacos.config.server.model.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * The type of nacos-all.
 *
 * @author 问道于盲
 * @date 2020-03-11
 */
@Service
@Transactional(rollbackFor = Throwable.class)
public class RolePersistServiceImpl {


    @Autowired
    private RolesRepository rolesRepository;

    public Page<RoleInfo> getRoles(int pageNo, int pageSize) {
        PageRequest pageRequest = PageRequest.of(pageNo - 1, pageSize);

        org.springframework.data.domain.Page<RolesEntity> datas = rolesRepository.findAll(pageRequest);
        List<RoleInfo> roles = datas.stream().map(this::convert).collect(Collectors.toList());
        Page<RoleInfo> page = new Page<>();
        page.setPageItems(roles);
        page.setPageNumber(pageNo);
        page.setTotalCount((int) datas.getTotalElements());
        page.setPagesAvailable(datas.getTotalPages());
        return page;
    }

    private RoleInfo convert(RolesEntity data) {
        RoleInfo role = new RoleInfo();
        role.setRole(data.getRole());
        role.setUsername(data.getUsername());
        return role;
    }

    public Page<RoleInfo> getRolesByUserName(String username, int pageNo, int pageSize) {

        PageRequest pageRequest = PageRequest.of(pageNo - 1, pageSize);

        org.springframework.data.domain.Page<RolesEntity> datas;
        if (StringUtils.isBlank(username)){
            datas = rolesRepository.findAll(pageRequest);
        }else {
            datas = rolesRepository.findAllByUsername(username, pageRequest);
        }
        List<RoleInfo> roles = datas.stream().map(this::convert).collect(Collectors.toList());

        Page<RoleInfo> page = new Page<>();
        page.setPageItems(roles);
        page.setPageNumber(pageNo);
        page.setTotalCount((int) datas.getTotalElements());
        page.setPagesAvailable(datas.getTotalPages());
        return page;
    }

    public void addRole(String role, String userName) {
        RolesEntity data = new RolesEntity();
        data.setRole(role);
        data.setUsername(userName);
        rolesRepository.save(data);
    }

    public void deleteRole(String role) {
        rolesRepository.deleteByRole(role);
    }

    public void deleteRole(String role, String username) {
        rolesRepository.deleteByUsernameAndRole(username, role);
    }
}
